#!/bin/bash

# ============================ 脚本变量 ============================
# 检测应用程序名
APP_NAME="td_tunnel_tcp"
# 等待应用程序启动超时时间
TIME_OUT_SEC=5



# ============================ 脚本函数 ============================
# 检查是否有相同参数的实例存在，如果有，则kill掉，保障同一vrf下只有一个实例在运行
check_vrf_is_running() {
    local vrf_id=$1
    local exist_pid_=$2
    if [[ -z "$exist_pid_" ]]; then
        return 0
    fi
    for pid in $exist_pid_; do
        vrf_id_from_pid=$(cat /proc/$pid/cmdline | tr '\0' ' ' | awk -F'--nf_queue_num ' '{print $2}' | cut -d ' ' -f1)
        if [[ $vrf_id_from_pid == $vrf_id ]]; then
            # echo "vrf$vrf_id is already running with PID $pid."
            kill -9 $pid
        fi
    done
}

# ============================ 脚本入口 ============================
if (( $# < 2 )); then
    echo "-1"
    # echo "err! need input vrf_name and local_bind_IP! eg: $0 1 10.0.32.222"
    exit 1
fi
VRFNAME=$1
VRFID=`echo $1 | awk -F'vrf' '{print $2}'`
LOCAL_IP=$2
WORK_MODE=$3

EXIST_PID=`pidof $APP_NAME`
params="--mode server --host_ip $LOCAL_IP --tunnel_srv_port 8000 --listen_port 9000 --nf_queue_num $VRFID --vrf_name $VRFNAME --net_mode $WORK_MODE"
# 校验当前vrf下是否已经存在实例（如果有，则kill掉）
check_vrf_is_running $VRFID $EXIST_PID 

# 启动tcp server
ip vrf exec vrf$VRFID bin/$APP_NAME $params | ./bash/handle_tcp_log.sh tcp_server_vrf$VRFID &

# 校验是否启动成功，并返回PID或错误码
TRY_COUNT=0
NEW_PID=`pidof $APP_NAME`
while [ $TRY_COUNT -lt $TIME_OUT_SEC ]; do
    if [[ -z "$NEW_PID" || "$EXIST_PID" == "$NEW_PID" ]]; then
        sleep 1
        TRY_COUNT=$(($TRY_COUNT + 1))
        NEW_PID=`pidof $APP_NAME`
        continue
    else
    arr1=($EXIST_PID)
    arr2=($NEW_PID)
    printf "%s\n" "${arr1[@]}" > temp1.txt
    printf "%s\n" "${arr2[@]}" > temp2.txt
    diff temp1.txt temp2.txt | grep '^>' | sed 's/^> //'
    rm temp1.txt temp2.txt
    exit 0
    fi
done
echo "-1"
echo "err! start tcp server failed! please check!"
exit 1

